#include "relay.h"
#include "systimer.h"
#include "system.h"

static RelayObj relay[RELAY_NUM] = {
    {Relay1, 0, GPIOB, GPIO_PIN_5},
    {Relay2, 0, GPIOB, GPIO_PIN_4},
    {Relay3, 0, GPIOB, GPIO_PIN_3},
    {Relay4, 0, GPIOA, GPIO_PIN_15},
};

void relay_init(void)
{
    rcu_periph_clock_enable(RCU_GPIOA);
    rcu_periph_clock_enable(RCU_GPIOB);
    gpio_pin_remap_config(GPIO_SWJ_SWDPENABLE_REMAP,ENABLE); 

    for(uint8_t i = 0; i < RELAY_NUM; i++)
    {
        gpio_init(relay[i].gpio_periph, GPIO_MODE_OUT_PP, GPIO_OSPEED_2MHZ, relay[i].pin);
        gpio_bit_reset(relay[i].gpio_periph, relay[i].pin);
    }
}

void relay_set(uint8_t id, uint8_t state)
{
    if(state != relay[id].state)
    {
        relay[id].state = state;
        gpio_bit_write(relay[id].gpio_periph, relay[id].pin, (bit_status)state);
        eeprom_write_one_byte(EEPROM_ADDR_RELAY1 + id, relay[id].state);
    }
}

void relay_toogle(uint8_t id)
{
    relay_set(id, !relay[id].state);
}

void relay_set_all(uint8_t state)
{
    for(uint8_t i = 0; i < RELAY_NUM; i++)
    {
        relay_set(i, state);
    }
}

uint8_t get_relay_state(uint8_t id)
{
    return relay[id].state;
}

// void relay_self_test(void)
// {
//     for(uint8_t i = 0; i < RELAY_NUM; i++)
//     {
//         relay_set((RelayID)i, 1);
//         delay_ms(5000);
//         relay_set((RelayID)i, 0);
//         delay_ms(5000);
//     }
// }
